import React, { Component } from 'react';
import { Button, Toast, List, InputItem, WhiteSpace, ActivityIndicator } from 'antd-mobile';
import WXJSAPI from '../WXJSAPI';
import {
    getSoundWavesAudio,
    delSoundWavesAudio,
    bindDevice,
    getopenid,
    getScanningDeviceSn,
    sleep,
    setDocumentTitle
} from '../utils';

const Item = List.Item;
class ScanBind extends Component {
    constructor(props, context) {
        super(props, context);
        this.appLogo = localStorage.getItem('app_logo');
        const deviceName = localStorage.getItem('device_name');
        const soundbindType = this.props.location.pathname.indexOf("soundbind") >= 0 ? 0 : 1;
        const ssid = localStorage.getItem('wifi_ssid') || '';
        const disabled = (ssid === '');
        this.state = {
            soundbindType: soundbindType,
            ssid: ssid,
            audioName: '',
            password: '',
            disabled: disabled,
            devices: [],
            showSearch: soundbindType === 1,
            binding: false,
            isPlaying: false,  // 播放声纹配网
            loopScan: false,
            deviceName: deviceName,
            url: '',
            isInit: false,
            scanText: '正在搜索..',
            markedWords: '注:长时间没有扫描到设备，请重启设备。',
            showListenBtn: false
        }
        this.clickTime = 0;
        this.deviceType = localStorage.getItem('device_type') || '';        
    }

    isEmpty(value) {
        return value === undefined || value === null;
    }

    initWxApi() {
        this.wxApi = new WXJSAPI((list) => {
            if (list.length === 0) {
                return;
            }
            let result = [];
            for (let index = 0; index < list.length; index++) {
                let device = list[index];
                if (device.deviceId.indexOf(this.deviceType) >= 0) {
                    let currentDevices = this.state.devices;
                    if (currentDevices.length === 0) {
                        result.push(device);
                        continue;
                    }
                    let isContrain = false;
                    for (let i = 0; i < currentDevices.length; i++) {
                        const item = currentDevices[i];
                        if (device.deviceId === item.deviceId) {
                            isContrain = true;
                            break;
                        }
                    }
                    if (!isContrain) {
                        result.push(device);
                    }
                }
            }
            if (result.length === 0) {
                return;
            }

            this.setState({
                showSearch: true,
                devices: result
            });
            // 扫描到设备,说明当前的wifi信息是有效的
            localStorage.setItem('wifi_ssid', this.state.ssid);
        }, () => {
            this.wxApi.scanDevice();
        });
    }

    // 调用下服务器接口，获取下ip地址
    async polingCheck() {
        await sleep(15000);
        // 设备已经扫描到不处理
        if (this.state.devices.length > 0) {
            return;
        }
        // 显示对应的提示文字，以及按钮
        this.setState({
            showListenBtn: true
        });
        this.getDeviceByIp();
    }

    async getDeviceByIp() {
        for (let index = 0; index < 2; index++) {
            const data = await getScanningDeviceSn();
            // 设备已经扫描到不处理
            if (this.state.devices.length > 0) {
                return;
            }
            if (data.errcode === 0) {
                if (data.data && data.data.indexOf(this.deviceType) >= 0) {
                    this.setState({
                        devices: [{ deviceId: data.data }]
                    });
                }
            }
            await sleep(4000);
        }
    }

    // 倒计时15秒
    async countDown() {
        for (let index = 15; index > 1; index--) {
            if(this._isMounted){
                this.setState({
                    scanText: `搜索中${index}秒`
                });
                await sleep(1000);
            }
        }
        this.setState({
            scanText: `正在搜索..`
        });
    }

    componentDidMount() {
        this._isMounted = true;
        this.initWxApi();
        if (this.state.soundbindType === 0) { // 来自声纹配置需要
            setDocumentTitle("第二步:配置设备上网和绑定")
            // ios端处理无法自动播放音频的问题
            document.addEventListener("WeixinJSBridgeReady", (function () {
                if (this.audio) {
                    this.audio.play();
                }
            }).bind(this), false);
            window.wx.ready(function () {
                try {
                    document.getElementById('audio').play();
                } catch (error) {
                    console.log(error);
                } finally {
                    if (this.audio) {
                        this.audio.play();
                    }
                }
            });
            this.setState({
                markedWords: ''
            });
        } else {
            setDocumentTitle("第二步:扫描设备和绑定")
            // 扫描倒计时
            this.countDown();
            this.polingCheck();
        }
        this.interval = setInterval(() => {
            if (this._isMounted) {
                if (this.state.soundbindType === 0) {
                    if (this.state.loopScan) {
                        this.wxApi.scanDevice();
                    }
                } else {
                    this.wxApi.scanDevice();
                }
            }

        }, 3000);
    }

    alredyListenVoice = () => {
        const startTime = new Date().getTime();
        if (startTime - this.clickTime <= 3000) {
            this.clickTime = startTime;
            return;
        }
        this.getDeviceByIp();
    }

    playAudio = () => {
        var pattern = /^[\u4E00-\u9FA5]/;
        if (pattern.test(this.state.ssid) || pattern.test(this.state.password)) {
            Toast.show('不支持带中文的wifi名称以及密码',2,false);
            return;
        }

        this.setState({
            isPlaying: true,
        });
        if (this.state.audioName !== '') {
            // 之前有新建过音频文件
            delSoundWavesAudio(this.state.audioName, () => { });
        }
        getSoundWavesAudio(this.state.ssid, this.state.password, (function (result) {
            if (result.errcode === 0) {
                const audioUrl = window.location.protocol + "//" + window.location.host + "/uploads/" + result.data;
                this.setState({
                    isInit: true,
                    url: audioUrl,
                    showSearch: true,
                    audioName: result.data,
                });
                this.audio.play();

            } else {
                Toast.fail('生成声波音频失败,请检查网络是否正常', 1, false);
                this.setState({
                    isPlaying: false,
                });
            }
        }).bind(this));
    }

    onError = (err) => {
        console.log(err);
        if (this.state.isInit) {
            Toast.fail('播放音频失败', 2, false);
            this.setState({
                isPlaying: false,
            });
            delSoundWavesAudio(this.state.audioName, () => { });
        }
    }

    onEnded = () => {
        this.setState({
            isPlaying: false,
        });
        delSoundWavesAudio(this.state.audioName, () => { });
        this.wxApi.scanDevice();
        this.setState({
            loopScan: true,
        });
        this.countDown();
        this.polingCheck();
    }

    // wifi名称
    wifiNameChange = (ssid) => {
        this.setState({
            ssid: ssid,
            disabled: ssid === ''
        });
    }

    //wifi密码
    wifiPasswordChange = (password) => {
        this.setState({
            password: password,
        });
    }

    onSelecteDevice(device) {
        this.setState({
            binding: true,
        });
        // 来自声纹类
        if (this.state.soundbindType === 0) {
            delSoundWavesAudio(this.state.audioName, () => { });
        }
        
        bindDevice(getopenid(), device.deviceId, this.state.deviceName, (data) => {
            this.setState({
                binding: false,
            });
            if (data.errcode === 0) {
                Toast.success("设备绑定成功", 2);
                setTimeout(() => {
                    this.wxApi.stopScan();
                    window.wx.closeWindow();
                }, 2200);
            } else {
                Toast.fail("绑定失败，请尝试重新绑定", 2, false);
            }
        })
    }

    componentWillUnmount() {
        this._isMounted = false;
        this.wxApi.stopScan();
        Toast.hide();
        if (this.interval) {
            clearInterval(this.interval);
        }
    }

    render() {
        return (
            <div >
                <audio
                    id="audio"
                    ref={(audio) => this.audio = audio}
                    src={this.state.url}
                    onError={this.onError}
                    onEnded={this.onEnded}
                    autoPlay={true} />
                {
                    this.state.soundbindType === 0 &&
                    <div>
                        <List renderHeader={() => '设备连接的Wi-Fi信息'}>
                            <InputItem
                                moneyKeyboardAlign="left"
                                clear
                                value={this.state.ssid}
                                pattern="/[^\u4e00-\u9fa5]+/"
                                placeholder=""
                                onChange={this.wifiNameChange}
                            ><span style={{ fontSize: "16px" }}>Wi-Fi名称</span></InputItem>
                            <InputItem
                                moneyKeyboardAlign="left"
                                clear
                                pattern="/[^\u4e00-\u9fa5]+/"
                                value={this.state.password}
                                onChange={this.wifiPasswordChange}
                                placeholder=""
                            ><span style={{ fontSize: "16px" }}>Wi-Fi密码</span></InputItem>
                        </List>
                        <WhiteSpace size="lg" />

                        <div style={{
                            display: "flex",
                            alignItems: "center",
                            width: '100%',
                            justifyContent: 'center',
                            marginTop: "24px"
                        }}>
                            <Button type="primary" style={{ width: '75%', fontSize: '15px' }}
                                disabled={this.state.disabled}
                                onClick={this.playAudio}>声波配置网络</Button>
                        </div>
                        <div style={{ marginTop: "20px", display: "flex", alignItems: "center", justifyContent: 'center'}}>
                            <span style={{
                                fontSize: '14px',
                                width: '95%',
                                textAlign: 'center',
                                color: '#212121',
                            }}>注:配网过程中,手机尽可能靠近设备,并保持周边安静。</span>
                        </div>
                    </div>

                }

                {
                    this.state.showSearch &&
                    <div>
                        <WhiteSpace size="lg" />
                        <List renderHeader={() => '发现周边设备'}>
                            {
                                this.state.devices.map((device, i) => {
                                    return (<Item
                                        style={{ height: "54px" }}
                                        key={i}
                                        thumb={this.appLogo}
                                        arrow="horizontal"
                                        extra="点击绑定"
                                        onClick={this.onSelecteDevice.bind(this, device)}
                                    >{this.state.deviceName}</Item>)
                                })
                            }
                            <InputItem
                                style={{ height: "48px" }}
                                moneyKeyboardAlign="left"
                                clear
                                placeholder=""
                                editable={false}
                                disabled={true}
                            >
                                <ActivityIndicator size="large" text={this.state.scanText} />
                            </InputItem>
                        </List>
                        <WhiteSpace size="lg" />
                        <div style={{display: "flex", alignItems: "center", justifyContent: 'center' }}>
                            {
                                this.state.showListenBtn &&
                                <p style={{ fontSize: '14px', width: '95%', textAlign: 'center', color: '#212121' }}>
                                    注:若扫描不到设备,请关机并重启设备,待听到设备发出语音 <span style={{ color: '#15a67c' }}>"我可以上网了"</span> 后,请点击  <span style={{ color: '#15a67c' }}>"确定已听到"</span>按钮。
                                </p>
                            }

                        </div>
                        <WhiteSpace size="lg" />
                    </div>

                }
                {
                    this.state.showListenBtn && <div style={{
                        display: "flex",
                        alignItems: "center",
                        width: '100%',
                        justifyContent: 'center',
                        marginBottom: '64px'
                    }}>
                        <Button
                            type="default"
                            style={{ width: '75%', fontSize: '15px' }}
                            onClick={this.alredyListenVoice}>确定已听到</Button>
                    </div>
                }

                {
                    this.state.binding && <ActivityIndicator toast text="正在绑定设备..." animating />
                }
                {
                    this.state.isPlaying && <ActivityIndicator toast text="声纹配网中..." animating />
                }
            </div>
        );
    }
}

export default ScanBind;